<!-- 保险公司编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="800"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="总计应收" prop="price">
        <el-input v-model="price" disabled style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="实收" prop="paid">
        <el-input v-model="form.paid" style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="垫付" prop="dianfu_amount">
        <el-input v-model="form.dianfu_amount" disabled style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="分期" prop="fenqi_benjin">
        <el-input v-model="form.fenqi_benjin" disabled style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="差价" prop="diff_price">
        <el-input v-model="diff_price" disabled style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="差价处理方式"
        prop="diff_price_type"
        v-if="diff_price != 0"
      >
        <el-radio-group v-model="form.diff_price_type">
          <el-radio-button
            v-for="item in diffPriceType"
            :key="item"
            :label="item"
          >
            {{ item }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="付款时间" prop="pay_time">
        <el-date-picker
          v-model="form.pay_time"
          class="filter-item"
          type="datetime"
          placeholder="付款时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 230px"
        />
      </el-form-item>

      <el-form-item label="付款图片" prop="pay_images">
        <image-upload :limit="99" v-model="form.pay_images" />
      </el-form-item>
    </el-form>
    <template
      #footer
      v-if="
        form.status == 0 ||
        form.status == 4 ||
        form.status == 3 ||
        form.status == 190
      "
    >
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import { updateTradePaid } from '@/api/company';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  import { jsJiafa } from '@/utils/my-common';
  import { ElMessage } from 'element-plus';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    status: 0,
    tax_price: '',
    qx_price: '',
    syx_price: '',
    qtx_price: '',

    glf_price: '', // 管理费
    glf_paid: '', // 管理费
    gps_price: '', // gps
    gps_paid: '', // gps
    eb_price: '', // 二保
    eb_paid: '', // 二保
    xx_price: '', // 学习
    xx_paid: '', // 学习
    gz_price: '', // 盖章
    gz_paid: '', // 盖章
    fw_price: '', // 法务
    fw_paid: '', // 法务
    qt_price: '', // 其他
    qt_paid: '', // 其他
    fenqi_benjin: '', // 分期的本金
    fenqi_amount: '',
    dianfu_amount: '',
    fenqi_charge_amount: '',
    fenqi_first_pay: '',
    price: '', // 总计
    paid: '', // 实际付款
    pay_images: '', // 付款图片
    pay_time: '', // 付款时间
    diff_price: 0,
    diff_price_type: '' // 差价处理方式
  });

  /** 表单验证规则 */
  const rules = reactive({
    pay_time: [
      {
        required: true,
        message: '请选择付款时间',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const checkDiffType = () => {
    var res = true;
    if (diff_price.value == 0) return true;
    if (diff_price.value > 0) {
      if (form.diff_price_type != '利润' && form.diff_price_type != '返还')
        return false;
    }
    if (diff_price.value < 0) {
      if (form.diff_price_type != '欠款' && form.diff_price_type != '优惠')
        return false;
    }
    return res;
  };

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      if (!checkDiffType()) {
        ElMessage.warning('请选择差价的处理方式');
        return;
      }
      loading.value = true;
      var requestData = Object.assign({}, form);
      // requestData.paid = paid.value;
      requestData.diff_price = diff_price.value;
      if (diff_price.value == 0) requestData.diff_price_type = '';
      updateTradePaid(requestData)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  // 差价
  const diff_price = computed(() => {
    var diff = 0;
    diff = paid.value - price.value;
    return diff.toFixed(2);
  });

  // 差价处理方式
  const diffPriceType = computed(() => {
    var list = [];
    if (diff_price.value > 0) {
      list = ['利润', '返还'];
    }
    if (diff_price.value < 0) {
      list = ['优惠', '欠款'];
    }
    return list;
  });

  // 计算总计应付
  const price = computed(() => {
    var price = 0;
    price = jsJiafa(price, form.tax_price);
    price = jsJiafa(price, form.qx_price);
    price = jsJiafa(price, form.syx_price);
    // price = jsJiafa(price, form.cpx_price);
    // price = jsJiafa(price, form.cyx_price);
    // price = jsJiafa(price, form.hyx_price);
    // price = jsJiafa(price, form.azx_price);
    // price = jsJiafa(price, form.jyx_price);
    price = jsJiafa(price, form.qtx_price);
    price = jsJiafa(price, form.glf_price);
    price = jsJiafa(price, form.gps_price);
    price = jsJiafa(price, form.eb_price);
    price = jsJiafa(price, form.xx_price);
    price = jsJiafa(price, form.fw_price);
    price = jsJiafa(price, form.gz_price);
    price = jsJiafa(price, form.fenqi_charge_amount);
    // price = jsJiafa(price, form.fenqi_first_pay);

    const totalQt =
      qtList.value.reduce((total, item) => {
        // 将金额转换为数字后累加，并乘以 100 以避免精度问题
        return total + Math.round(parseFloat(item.price || 0) * 100);
      }, 0) / 100; // 最后除以 100 恢复原始金额
    price = jsJiafa(price, totalQt);
    return price;
  });
  // 实际支付了多少，实付+分期+垫付  用来计算差价
  const paid = computed(() => {
    var paid = 0;
    paid = jsJiafa(paid, form.paid);
    paid = jsJiafa(paid, form.dianfu_amount);
    paid = jsJiafa(paid, form.fenqi_benjin);

    return paid;
  });

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };
  const title = ref('');
  const qtList = ref([
    {
      title: '',
      price: ''
    }
  ]);
  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        title.value = props.data.plate_number + '的实际付款';
        if (props.data) {
          assignFields({
            ...props.data
          });
          qtList.value = props.data.qtList;
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
